package fluxx.draft;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.InputMismatchException;
import java.util.Scanner;

public class Test1 implements PropertyChangeListener {
	static final int NUM_PLAYERS = 2;
	Player[] players = new Player[NUM_PLAYERS];
	private int turnIndex;
	public static void main (String[] args) {
		Test1 test = new Test1();
		test.runTest();
	}
	public void runTest() {
		// Start new game with some printing
		GameState myGame = new GameState(new StandardDeck(), NUM_PLAYERS);
		myGame.addListener(this);
		printState(myGame);
		
		// Take turns and print every step
		for (int i = 0; i < 100; i++) { // Loop until game ends (goal is met) or 100 (safety)
			Player player = myGame.currentPlayer();
			
			// Player draws a card
			Card drawnCard = myGame.takeFresh();
			player.give(drawnCard);
			System.out.print(player.getName()+" draws "+drawnCard);
			
			// Player plays random card
			CardSet playedCards = new CardSet();
			int thisTurnIndex = turnIndex;
			while (thisTurnIndex == turnIndex) {
				int pick = inputInt("Choose card to play: {"+player.getHand()+"}");
				//Card playedCard = myGame.demandPickOne(player.getHand(), "Choose card to play");
				Card playedCard = player.getHand().get(pick);
				playedCards.add(playedCard);
				try {
					myGame.playCard(player, playedCard);
				} catch (GameOverException exc) {
					System.out.println(" and plays "+playedCards);
					printState(myGame);
					System.out.println(exc.getWinner().getName()+" wins the game.");
					System.exit(0);
				}
			}
			System.out.println(" and plays "+playedCards);
			printState(myGame);
		}
		System.out.println("Test is over.");
	}
	
	public static void printState(GameState game) {
		StringBuffer buffer = new StringBuffer();
		buffer.append("Deck: "+game.getFreshCards().size()+". ");
		buffer.append("Discarded: "+game.getDiscardPile().size()+". ");
		buffer.append("Goal: "+game.goal+", rules: "+game.rules+"\n");
		for (Player player : game.players) {
			buffer.append(player+"\n");
		}
		System.out.println(buffer);
	}
	public static int inputInt(String message) {
		System.out.println(message);
		boolean ok = false;
		int input = -1; // Fy
		while (!ok) {
			System.out.print("# ");
			Scanner scanner = new Scanner(System.in);
			try {
				input = scanner.nextInt();
				ok = true;
			} catch (InputMismatchException exc) {
				ok = false;
			}
		}
		return input;
	}
	@Override
	public void propertyChange(PropertyChangeEvent evt) {
		// TODO Auto-generated method stub
		if (evt.getPropertyName() == "pass turn") {
			turnIndex++;
		}
	}
}
